<template>
  <section>
    <!--工具条-->
    <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
      <el-form :inline="true" :model="filters">
        <!-- <el-form-item>
          <el-input v-model="filters.id" placeholder="ID"></el-input>
        </el-form-item> -->
        <!-- <el-form-item>
          <el-input v-model="filters.productId" placeholder="产品ID"></el-input>
        </el-form-item> -->
        <el-form-item>
          <el-select size="small" style="width:200px;" v-model="filters.branchCode" @change="selectVal" placeholder="请选择机构">
            <!-- <el-option v-for="(item,index) in filters.barchCodes" :key="index" :label="item.codeCname" :value="item.code"></el-option> -->
            <el-option label="总公司" value="0000"></el-option>
            <!-- <el-option label="全部地区" value=""></el-option>
            <el-option label="重庆" value="1"></el-option>
            <el-option label="北京" value="2"></el-option> -->
            <!-- <el-option v-for="item in items" label="重庆"   value="1"></el-option> -->
          </el-select>
        </el-form-item>
        <!--         <el-form-item>
          <el-button type="primary" v-on:click="getHots">查询</el-button>
        </el-form-item> -->
        <!-- <el-form-item v-show="isWhole">
          <el-button type="primary" @click="Addhot">添加热销</el-button>
        </el-form-item> -->
        <el-form-item style="float:right;">
          <el-button size="small" type="primary" icon="upload2" @click="exportExcels" v-show="exportBtnVisible">导出</el-button>
        </el-form-item>
      </el-form>
    </el-col>

    <!--列表-->
    <el-table ref="multipleTable" :data="products" stripe border :height="winHeight-188" highlight-current-row v-loading="listLoading" @selection-change="selsChange" @cell-click="dblclick" style="width: 100%;">
      <!-- <el-table-column type="selection" :render-header="renderHeader"   width="55">
      </el-table-column> -->
      <el-table-column label="是否热销" align="center" fixed='left' width="115">
        <template scope="scope">
          <el-checkbox :value="Ishot(scope.$index, scope.row)" @change="handleHot(scope.$index, scope.row, $event)"></el-checkbox>
        </template>
      </el-table-column>
      <el-table-column prop="serialNo" label="序号" width="100" align="center" sortable>
        <template scope="scope">
          <span style="color:#20a0ff;cursor:pointer;text-decoration:underline;">{{scope.row.serialNo}}</span>
        </template>
      </el-table-column>
      <!-- <el-table-column prop="id" label="ID" width="180"  sortable>
      </el-table-column> -->
      <el-table-column prop="productCname" label="产品中文名" width="180" sortable show-overflow-tooltip>
      </el-table-column>
      <el-table-column prop="productEname" label="产品英文名" width="180" sortable show-overflow-tooltip>
      </el-table-column>
      <el-table-column prop="riskCode" label="险种" min-width="150" :formatter="formatRisk" sortable>
      </el-table-column>
      <!-- <el-table-column prop="hotFlag" label="是否热销" width="120" :formatter="formathotFlag" sortable>
      </el-table-column> -->
      <el-table-column prop="startDate" label="有效起期" width="120" sortable>
      </el-table-column>
      <el-table-column prop="endDate" label="有效止期" min-width="180" sortable>
      </el-table-column>
      <!-- <el-table-column prop="deadLine" label="保障期限" min-width="120" sortable>
      </el-table-column> -->
      <el-table-column prop="maxDeadLine" label="最大期限" min-width="120" sortable>
      </el-table-column>
      <el-table-column prop="minDeadLine" label="最小期限" min-width="120" sortable>
      </el-table-column>
      <el-table-column prop="maxAge" label="最大年龄" min-width="120" sortable>
      </el-table-column>
      <el-table-column prop="minAge" label="最小年龄" min-width="120" sortable>
      </el-table-column>
      <el-table-column prop="quantity" label="销量" min-width="120" sortable>
      </el-table-column>
      <el-table-column prop="priPrice" label="原价" min-width="120" sortable>
      </el-table-column>
      <el-table-column prop="discountPrice" label="折扣价" min-width="120" sortable>
      </el-table-column>
      <el-table-column prop="minPrice" label="最低价格" min-width="120" sortable>
      </el-table-column>
    </el-table>

    <!--工具条-->
    <el-col :span="24" class="toolbar">
      <!--  <el-button type="danger" @click="batchRemove"  v-show="isWhole" :disabled="this.sels.length===0">批量取消</el-button> -->
      <el-pagination style="float:right" @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="page" :page-sizes="[10, 20, 40, 80]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </el-col>
    <!--添加热销界面-->
    <el-dialog title="添加热销" size="large" v-model="hotsVisible" :close-on-click-modal="false">
      <el-table :data="hots" stripe border height='480' highlight-current-row v-loading="listLoading" @selection-change="hotselsChange" style="width: 100%;">

        <el-table-column prop="id" label="ID" width="120" sortable>
        </el-table-column>
        <el-table-column prop="productCname" label="产品中文名" width="180" sortable>
        </el-table-column>
        <el-table-column prop="productEname" label="产品英文名" width="180" sortable>
        </el-table-column>
        <el-table-column prop="riskCode" label="险种" min-width="150" :formatter="formatRisk" sortable>
        </el-table-column>
        <!-- <el-table-column prop="hotFlag" label="是否热销" width="120" :formatter="formathotFlag" sortable>
      </el-table-column> -->
        <el-table-column prop="startDate" label="有效起期" width="120" sortable>
        </el-table-column>
        <el-table-column prop="endDate" label="有效止期" min-width="180" sortable>
        </el-table-column>
        <el-table-column prop="deadLine" label="保障期限" min-width="120" sortable>
        </el-table-column>
        <el-table-column prop="maxAge" label="最大年龄" min-width="120" sortable>
        </el-table-column>
        <el-table-column prop="minAge" label="最小年龄" min-width="120" sortable>
        </el-table-column>
        <el-table-column prop="quantity" label="销量" min-width="120" sortable>
        </el-table-column>
        <el-table-column prop="priPrice" label="原价" min-width="120" sortable>
        </el-table-column>
        <el-table-column prop="discountPrice" label="折扣价" min-width="120" sortable>
        </el-table-column>
        <el-table-column prop="minPrice" label="最低价格" min-width="120" sortable>
        </el-table-column>
        <el-table-column fixed='right' type="selection" width="55">
        </el-table-column>
        <!-- <el-table-column label="操作" fixed='right' width="150">
        <template scope="scope">
        <el-checkbox ></el-checkbox>
        </template>
      </el-table-column> -->
      </el-table>
      <!--工具条-->
      <el-col :span="24" class="toolbar">
        <el-pagination layout="prev, pager, next" @current-change="handleCurrentChanges" :page-size="10" :total="totals" style="float:right;">
        </el-pagination>
      </el-col>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="hotsVisible = false">取消</el-button>
        <el-button type="primary" :disabled="this.hotsels.length===0" @click.native="batchAdd" :loading="addLoading">添加</el-button>
      </div>
    </el-dialog>
    <!-- 热销 -->
    <el-dialog title="设置序号" v-model="hotFormVisible" size="tiny" :close-on-click-modal="false">
      <el-form :model="hotForm" label-width="120px" :rules="hotFormRules" ref="hotForm">
        <el-form-item label="热销序号" prop="name">
          <el-input v-model="hotForm.serialNo" auto-complete="off"></el-input>
        </el-form-item>
        <!-- <el-form-item  label="地区" prop="name">
                    <el-select  v-model="hotForm.branchCode"   placeholder="地区">
                      <el-option label="重庆" value="1"></el-option>
                      <el-option label="北京" value="2"></el-option>
                    </el-select>
              </el-form-item> -->
        <!-- <el-form-item label="备注" prop="name">
                <el-input  type="textarea"  v-model="hotForm.remark" auto-complete="off"></el-input>
              </el-form-item> -->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="hotFormVisible = false">取消</el-button>
        <el-button type="primary" @click.native="hotSubmit" :loading="editLoading">提交</el-button>
      </div>
    </el-dialog>
  </section>
</template>

<script>
import util from '../../common/js/util'
import { mapState, mapActions } from 'vuex'
import commons from '../../common/js/common'
//import NProgress from 'nprogress'
import { removeProduct, batchRemoveUser, editProduct, addProduct, editHot, getHotProduct, removeHotProduct, getUserListPage, addToAreaHot, codeNodeList, branchHotProductList, updateProductSerialNo } from '../../api/api';

export default {
  data() {
    return {
      filters: {
        branchCode: '',
        barchCodes: ''
      },
      products: [],
      hots: [],
      total: 0,
      totals: 0,
      page: 1,
      pages: 1,
      pageSize: 10,
      exportTotal: 0,
      loading: '',
      lists: [],
      rowID: '',
      branchCodes: '',
      listLoading: false,
      hotlist: [],
      sels: [],//列表选中列
      hotsels: [],//列表选中列
      ishotValue: false,
      hotsVisible: false,
      isWhole: false,//添加热销是否显示
      editFormVisible: false,//修改界面是否显示
      hotFormVisible: false,//热销界面是否显示
      exportBtnVisible: false,
      editLoading: false,
      editFormRules: {
        // name: [
        //   { required: true, message: '请输入姓名', trigger: 'blur' }
        // ]
      },
      hotFormRules: {

      },
      addLoading: false,
      hotForm: {
        productId: '',
        branchCode: '',
        remark: '',
        serialNo: '',
        introduceUrl: ''
      }
    }
  },
  computed: mapState({
    clist: 'riskCodelist',
    blist: 'branchCodelist',
    winHeight: 'winHeight'
  }),
  methods: {
    ShowFileName: function () {
      let files = $("#file").files;
      // for(var i = 0; i < files.length; i++) {
      //   var file = files[i];
      //   this.addForm.imgUrl = file;
      // }
    },
    //险种编码转换
    formatRisk: function (row, column) {
      return row.riskCode == '2725' ? '个意险' : (row.riskCode == '2726' ? '旅行险' : '家财险');
    },
    formatOrg: function (row, column) {
      return row.organizationId && row.organizationId.name ? row.organizationId.name : '-';
    },
    renderHeader: function () {
      return "1";
    },
    selectVal: function () {
      if (this.filters.branchCode) {
        this.isWhole = true;
      }
      else {
        this.isWhole = false;
      }
      this.getHots(true);
    },
    Addhot: function () {
      this.hotsVisible = true;
      this.getHotsproduct();
    },
    //排序
    sort(a, b) {
    },
    dblclick(row, column, cell, event) {
      this.rowID = row.xid;
      if (column.label == '序号') {
        this.hotFormVisible = true;
        this.hotForm.serialNo = row.serialNo;
      }
    },
    handleCurrentChange(val) {
      this.page = val;
      this.getHots(true);
      this.$refs.multipleTable.clearSelection();
    },
    handleCurrentChanges(val) {
      this.pages = val;
      this.getHotsproduct();
    },
    handleSizeChange(val) {
      this.pageSize = val;
      this.getHots(true);
    },
    getHotsproduct() {
      let para = new FormData();
      para.append("pageSize", 10);
      para.append("pageNumber", this.pages);
      para.append("productCname", '');
      para.append("riskCode", '');
      para.append("startDate", '');
      para.append("endDate", '');
      para.append("branchCode", this.filters.branchCode);
      this.listLoading = true;
      //NProgress.start();
      getUserListPage(para).then((res) => {
        this.totals = res.data.result.totalElements;
        this.hots = res.data.result.content;
        this.listLoading = false;
      });


    },
    //获取用户列表
    getHots(bool) {
      let list = new FormData();
      let para = new FormData();
      para.append("pageSize", bool ? this.pageSize : this.exportTotal);
      para.append("pageNumber", bool ? this.page : 1);
      para.append("productCname", '');
      para.append("riskCode", '');
      para.append("startDate", '');
      para.append("endDate", '');
      para.append("branchCode", bool ? this.filters.branchCode : this.branchCodes);
      list.append("type", "BranchCode");
      this.branchCodes = this.filters.branchCode;
      this.listLoading = bool;
      //NProgress.start();
      if (!bool) {
        this.loading = this.$loading({
          lock: true,
          text: '正在导出',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });
      }
      // codeNodeList(list).then((res) => {
      // });

      branchHotProductList(para).then((res) => {
        this.total = res.data.result.total;
        this.exportTotal = res.data.result.total;
        this.lists = commons.hotSort(res.data.result.list);
        this.listLoading = false;
        if (!bool) {
          this.loading.close();
          this.export2Excel();
        }
        else {
          this.products = commons.hotSort(res.data.result.list);
          let branchList = new FormData();

          branchList.append("type", "BranchCode");

          // codeNodeList(branchList).then((res) => {
          //   this.filters.barchCodes = res.data.result;
          // });
        }
        // NProgress.done();
      });


    },
    //获取机构
    getbarch() {
      let branchList = new FormData();

      branchList.append("type", "BranchCode");

      codeNodeList(branchList).then((res) => {
        this.filters.barchCodes = res.data.result;
      });
    },
    //初始热销
    Ishot(index, row) {
      try {
        return row.hotFlag;
      }
      catch (error) {
        return false;
      }

    },
    //删除
    handleDel: function (index, row) {
      this.$confirm('确认删除该记录吗?', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true;
        //NProgress.start();
        let para = new FormData();
        para.append("ids", row.id);
        removeProduct(para).then((res) => {
          this.listLoading = false;
          //NProgress.done();
          this.$message({
            message: '删除成功',
            type: 'success'
          });
          this.getHots(true);
        });
      }).catch(() => {

      });
    },

    //table导出excel
    exportExcels: function () {
      this.getHots(false);
    },
    export2Excel: function () {
      require.ensure([], () => {
        const { export_json_to_excel } = require('../../vendor/Export2Excel');
        const tHeader = ['序号', '是否热销', '产品中文名', '产品英文名', '险种', '有效起期', '有效止期', '最大期限', '最小期限', '最大年龄', '最小年龄', '销量', '原价', '折扣价', '最低价格'];
        const filterVal = ['id', 'hotFlag', 'productCname', 'productEname', 'riskCode', 'startDate', 'endDate', 'maxDeadLine', 'minDeadLine', 'maxAge', 'minAge', 'quantity', 'priPrice', 'discountPrice', 'minPrice'];
        const list = this.lists;
        for (var i in list) {
          list[i].hotFlag = list[i].hotFlag ? '是' : '否';
          list[i].riskCode = commons.CodeName(this.clist, list[i].riskCode, "RiskCode");
        }
        const data = this.formatJson(filterVal, list);
        export_json_to_excel(tHeader, data, '热销产品列表excel');
      })
    },
    formatJson: function (filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => v[j]))
    },

    //显示修改界面
    handleEdit: function (index, row) {
      this.editFormVisible = true;
      this.editForm = Object.assign({}, row);
    },
    //显示热销界面
    handleHot: function (index, row, event) {
      if (row.hotFlag == false) {
        let para = new FormData();
        para.append("branchCode", this.filters.branchCode);
        para.append("ids", row.id);
        addToAreaHot(para).then((res) => {
          // this.addLoading = false;
          //NProgress.done();
          row.hotFlag = true;
          this.getHots(true);
        });
      }
      else {
        let para = new FormData();
        para.append("branchCode", this.filters.branchCode);
        para.append("ids", row.id);
        removeHotProduct(para).then((res) => {
          row.hotFlag = false;
          this.getHots(true);
        });
      }

    },
    //显示新增界面
    handleAdd: function () {
      this.addFormVisible = true;
      this.addForm = {
        // id: '',
        productCname: '',
        productEname: '',
        productType: '',
        serialNo: '',
        riskCode: '',
        isShow: '',
        quantity: '',
        priPrice: '',
        discountPrice: '',
        minPrice: '',
        introduceUrl: '',
        schemeUrl: '',
        imgUrl: '',
        remark: '',
        detailUrl: '',
        descrition: '',
        detail: '',
        deadLine: '',
        maxAge: '',
        minAge: '',
        startDate: '',
        endDate: '',
        tbSpHotproduct: {
          branchCode: '',
          remark: '',
          serialNo: '',
          introduceUrl: ''
        }
      };
    },
    //修改
    editSubmit: function () {
      this.$refs.editForm.validate((valid) => {
        if (valid) {
          this.$confirm('确认提交吗？', '提示', {}).then(() => {
            this.editLoading = true;
            //NProgress.start();
            let para = Object.assign({}, this.editForm);
            para.startDate = (!para.startDate || para.startDate == '') ? '' : util.formatDate.format(new Date(para.startDate), 'yyyy-MM-dd');
            para.endDate = (!para.endDate || para.endDate == '') ? '' : util.formatDate.format(new Date(para.endDate), 'yyyy-MM-dd');
            editProduct(para).then((res) => {
              this.editLoading = false;
              //NProgress.done();
              this.$message({
                message: '提交成功',
                type: 'success'
              });
              this.$refs['editForm'].resetFields();
              this.editFormVisible = false;
              this.getHots(true);
            });
          });
        }
      });
    },
    //热销
    hotSubmit: function () {
      this.$refs.hotForm.validate((valid) => {
        if (valid) {
          this.$confirm('确认提交吗？', '提示', {}).then(() => {
            this.addLoading = true;
            let para = new FormData;
            para.append("id", this.rowID);
            para.append("serialNo", this.hotForm.serialNo);
            updateProductSerialNo(para).then((res) => {
              this.addLoading = false;
              //NProgress.done();
              this.$message({
                message: '提交成功',
                type: 'success'
              });
              this.$refs['hotForm'].resetFields();
              this.hotFormVisible = false;
              this.getHots(true);
            });
          });
        }
      });
    },
    selsChange: function (sels) {
      this.sels = sels;
    },
    hotselsChange: function (hotsels) {
      this.hotsels = hotsels;
    },
    //取消热销
    cancelHot: function (index, row) {
      if (!this.filters.branchCode) {
        this.$message.error('请选择地区再取消');
      } else {
        this.$confirm('确认取消该产品热销吗?', '提示', {
          type: 'warning'
        }).then(() => {
          this.listLoading = true;
          //NProgress.start();
          let para = new FormData();
          para.append("branchCode", this.filters.branchCode);
          para.append("ids", row.id);
          removeHotProduct(para).then((res) => {
            this.listLoading = false;
            //NProgress.done();
            this.$message({
              message: '取消成功',
              type: 'success'
            });
            this.getHots(true);
          });
        }).catch(() => {

        });
      }

    },
    //批量添加热销
    batchAdd: function () {
      var ids = this.hotsels.map(item => item.id).toString();
      this.$confirm('确认添加吗？', '提示', {}).then(() => {
        this.addLoading = true;
        //NProgress.start();
        let para = new FormData();
        para.append("branchCode", this.filters.branchCode);
        para.append("ids", ids);
        addToAreaHot(para).then((res) => {
          this.addLoading = false;
          //NProgress.done();
          this.$message({
            message: '添加成功',
            type: 'success'
          });
          this.hotsVisible = false;
          this.getHots(true);
        });
      });
    },
    //批量取消
    batchRemove: function () {
      var ids = this.sels.map(item => item.id).toString();
      this.$confirm('确认取消选中记录吗？', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true;
        let para = new FormData();
        para.append("branchCode", this.filters.branchCode);
        para.append("ids", ids);
        removeHotProduct(para).then((res) => {
          this.listLoading = false;
          //NProgress.done();
          this.$message({
            message: '取消成功',
            type: 'success'
          });
          this.getHots(true);
        });
      }).catch(() => {

      });
    },
    btnShow: function () {
      let thisData = JSON.parse(sessionStorage.getItem('153'));
      let _this = this;
      $.each(thisData, function (i, j) {
        if (thisData[i] == "hotSaleExport") {
          _this.exportBtnVisible = true;
        }
      });
    }
  },
  mounted() {
    // this.getHots();
    // this.getbarch();
    this.btnShow();
  }
}

</script>

<style scoped>

</style>